package com.haoshuang.zhouzhoubang.ui.adapter

import android.content.Context
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnLongClickListener
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ItemUploadViewBinding
import com.haoshuang.zhouzhoubang.widget.UploadFileBean
import com.luck.picture.lib.config.PictureMimeType
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.imageResource
import com.mufeng.libs.utils.view.invisible
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone

class UploadViewAdapter(private val context: Context, result: MutableList<UploadFileBean>, private val defaultSrc: Int = R.drawable.ic_add_image) :
    RecyclerView.Adapter<UploadViewAdapter.ViewHolder>() {

    companion object {
        const val TAG = "UploadView"
        const val TYPE_CAMERA = 1
        const val TYPE_PICTURE = 2
    }

    private val list = arrayListOf<UploadFileBean>()
    private var mInflater: LayoutInflater = LayoutInflater.from(context)

    private var selectMax = 9


    private var isCanEdit = true

    fun setCanEdit(isEdit: Boolean){
        this.isCanEdit = isEdit
        notifyDataSetChanged()
    }

    init {
        list.addAll(result)
    }

    fun delete(position: Int) {
        try {
            if (position != RecyclerView.NO_POSITION && list.size > position) {
                list.removeAt(position)
                notifyItemRemoved(position)
                notifyItemRangeChanged(position, list.size)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun setSelectMax(selectMax: Int) {
        this.selectMax = selectMax
    }

    fun getSelectMax(): Int {
        return selectMax
    }

    fun getData(): MutableList<UploadFileBean> {
        return list
    }

    fun remove(position: Int) {
        if (position < list.size) {
            list.removeAt(position)
        }
    }

    override fun getItemCount(): Int {
        return if (list.size < selectMax && isCanEdit) {
            list.size + 1
        } else {
            list.size
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (isShowAddItem(position)) {
            TYPE_CAMERA
        } else {
            TYPE_PICTURE
        }
    }

    private fun isShowAddItem(position: Int): Boolean {
        val size = list.size
        return position == size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = mInflater.inflate(R.layout.item_upload_view, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // 少于MaxSize张, 显示继续添加的图标
        if (getItemViewType(position) == TYPE_CAMERA) {
            holder.binding.ivImage.imageResource = defaultSrc
            holder.binding.ivImage.clickWithTrigger {
                if (mItemClickListener != null) {
                    mItemClickListener!!.openPicture()
                }
            }
            holder.binding.ivDel.invisible()
        } else {
            holder.binding.ivDel.clickWithTrigger {
                if (!isCanEdit)return@clickWithTrigger
                val index = holder.absoluteAdapterPosition
                if (index != RecyclerView.NO_POSITION && list.size > index) {
                    list.removeAt(index)
                    notifyItemRemoved(index)
                    notifyItemRangeChanged(index, list.size)
                }
            }
            val media = list[position]
            val path = if (media.url.isNullOrEmpty())media.localMedia?.realPath else media.url
            holder.binding.ivVideo.visibleOrGone(media.isVideo)
            Glide.with(holder.itemView.context)
                .load(
                    if (media.url.isNullOrEmpty()){
                        if (PictureMimeType.isContent(path) && media.localMedia?.isCut == false && media.localMedia?.isCompressed == false)
                            Uri.parse(path)
                        else
                            path
                    }else{
                        path
                    }
                )
                .centerCrop()
                .placeholder(R.color.c_f6)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(holder.binding.ivImage)

            // 上传状态
            when(media.status){
                0 -> {
                    // 未上传
                    holder.binding.llUpload.gone()
                    holder.binding.ivDel.visibleOrGone(isCanEdit)
                }
                1 -> {
                    // 上传中
                    holder.binding.llUpload.visible()
                    holder.binding.ivRetry.gone()
                    holder.binding.tvUploadProgress.visible()
                    holder.binding.tvUploadProgress.text = "${media.progress}%"
                    holder.binding.tvUploadStatus.visible()
                    holder.binding.tvUploadStatus.text = "上传中"
                    holder.binding.ivDel.gone()
                }
                2 -> {
                    // 上传成功
                    holder.binding.llUpload.gone()
                    holder.binding.ivDel.visibleOrGone(isCanEdit)
                }
                3 -> {
                    // 上传失败
                    holder.binding.llUpload.visible()
                    holder.binding.ivRetry.visible()
                    holder.binding.tvUploadProgress.gone()
                    holder.binding.tvUploadStatus.visible()
                    holder.binding.tvUploadStatus.text = "点击重试"
                    holder.binding.ivDel.visibleOrGone(isCanEdit)
                }
            }

            //itemView 的点击事件
            if (mItemClickListener != null) {
                holder.itemView.clickWithTrigger { v: View? ->
                    val adapterPosition: Int = holder.getAbsoluteAdapterPosition()
                    mItemClickListener!!.onItemClick(v!!, adapterPosition)
                }
            }

            if (mItemLongClickListener != null) {
                holder.itemView.setOnLongClickListener { v: View? ->
                    val adapterPosition: Int = holder.getAbsoluteAdapterPosition()
                    mItemLongClickListener!!.onItemLongClick(holder, adapterPosition, v)
                    true
                }
            }
        }
    }

    class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
        val binding = ItemUploadViewBinding.bind(view)
    }

    private var mItemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(l: OnItemClickListener?) {
        mItemClickListener = l
    }

    interface OnItemClickListener {
        /**
         * Item click event
         *
         * @param v
         * @param position
         */
        fun onItemClick(v: View, position: Int)

        /**
         * Open PictureSelector
         */
        fun openPicture()
    }

    private var mItemLongClickListener: OnItemLongClickListener? = null

    fun setItemLongClickListener(l: OnItemLongClickListener?) {
        mItemLongClickListener = l
    }

    interface OnItemLongClickListener {
        fun onItemLongClick(holder: RecyclerView.ViewHolder?, position: Int, v: View?)
    }

}